/*
 * Copyright (c) 2022-2024 KCloud-Platform-IoT Author or Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.mezz.bones.framework.base.context;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.ttl.TransmittableThreadLocal;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Optional;

/**
 * 用户请求上下文 方便请求域中获取用户请求相关信息
 *
 * @author mezz
 */
public class RequestContextHolder {

	/**
	 * 用户上下文本地线程变量.
	 */
	private static final ThreadLocal<RequestContext> USER_REQUEST_LOCAL = new TransmittableThreadLocal<>();

	/**
	 * 注销本地线程变量.
	 */
	public static void clear() {
		USER_REQUEST_LOCAL.remove();
	}

	/**
	 * 获取本地线程变量.
	 * @return 用户
	 */
	public static RequestContext get() {
		return Optional.ofNullable(USER_REQUEST_LOCAL.get()).orElse(new RequestContext());
	}

	/**
	 * 往本地线程变量写入.
	 * @param user 用户
	 */
	public static void set(RequestContext user) {
		USER_REQUEST_LOCAL.set(user);
	}

	/**
	 * 用户.
	 */
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	public static class RequestContext {

		/**
		 * ID
		 */
		private String loginId;

		/**
		 * 登录的用户信息
		 */
		private RequestLoginUserInfo loginUserInfo;

		/**
		 * 接口版本号
		 */
		private String version;

		/**
		 * 请求客户端信息
		 */
		private String userAgent;

		/**
		 * 请求设备
		 */
		private String device;

		/**
		 * 请求路径
		 */
		private String reqUrl;

		/**
		 * 客户端IP
		 */
		private String ip;

		/**
		 * 租户ID
		 */
		private String tenantId;

	}

	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	public static class RequestLoginUserInfo {

		/**
		 * 当前登录账号 (手机号、邮箱、用户名)
		 */
		private String loginAccount;

		/**
		 * 当前登录的用户名/昵称
		 */
		private String loginUserName;
	}

	public static void main(String[] args) {

		String userAgentStr = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/130.0.0.0";
		// 解析 User-Agent
		UserAgent userAgent = UserAgentUtil.parse(userAgentStr);

		// 获取浏览器名称和版本
		System.out.println("Browser: " + userAgent.getBrowser().getName());
		System.out.println("Browser Version: " + userAgent.getVersion());

		// 获取操作系统名称
		System.out.println("Operating System: " + userAgent.getOs().getName());
	}

}
